﻿Imports Elmah

Public Class ElmahHandleErrorAttribute
    Inherits HandleErrorAttribute

    Public Overrides Sub OnException(ByVal context As ExceptionContext)
        MyBase.OnException(context)

        Dim e = context.Exception
        ' if unhandled, will be logged anyhow
        ' prefer signaling, if possible
        If Not context.ExceptionHandled OrElse RaiseErrorSignal(e) OrElse IsFiltered(context) Then
            ' filtered?
            Return
        End If

        LogException(e)
    End Sub

    Private Shared Function RaiseErrorSignal(ByVal e As Exception) As Boolean
        Dim context = HttpContext.Current
        If context Is Nothing Then
            Return False
        End If
        Dim signal = ErrorSignal.FromContext(context)
        If signal Is Nothing Then
            Return False
        End If
        signal.Raise(e, context)
        Return True
    End Function

    Private Shared Function IsFiltered(ByVal context As ExceptionContext) As Boolean
        Dim config = TryCast(context.HttpContext.GetSection("elmah/errorFilter"), ErrorFilterConfiguration)

        If config Is Nothing Then
            Return False
        End If

        Dim testContext = New ErrorFilterModule.AssertionHelperContext(context.Exception, HttpContext.Current)

        Return config.Assertion.Test(testContext)
    End Function

    Private Shared Sub LogException(ByVal e As Exception)
        Dim context = HttpContext.Current
        ErrorLog.GetDefault(context).Log(New [Error](e, context))
    End Sub
End Class
